package com.ruoyi.mongo.cet4.service.impl;

import com.ruoyi.mongo.cet4.service.ComprehensiveInterface;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.mongo.service.MongoConstants;
import com.ruoyi.mongo.comprehensive.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Data
@Service
public class ComprehensiveService implements ComprehensiveInterface {

    private final MongoTemplate comprehensiveTemplate;

    public ComprehensiveService(@Qualifier("comprehensiveTemplate") MongoTemplate comprehensiveTemplate) {
        this.comprehensiveTemplate = comprehensiveTemplate;
    }

    @Override
    public List<ExamRecord> selectExamDataList(ExamData examData) {
        List<ExamRecord> list = comprehensiveTemplate.findAll(ExamRecord.class);
        if (!list.isEmpty()) {
            return list;
        }
        return null;
    }

    @Override
    public List<ReadingAnswer> selectQueryRecordDetail(String id) {
        Query query = Query.query(Criteria.where(MongoConstants.MONGO_PRACTICE).is(id));
        return comprehensiveTemplate.find(query, ReadingAnswer.class);
    }

    @Override
    public List<ExamRecord> selectQueryRecordList(ExamData examData) {
        Query query = getComprehensiveQuery(examData);
        Sort sort = Sort.by(Sort.Direction.DESC, MongoConstants.MONGO_TIME_SORTED);
        query.with(sort);
        query.limit(MongoConstants.MONGO_PAGE_SIZE);

        List<ExamRecord> list = comprehensiveTemplate.find(query,ExamRecord.class);
        if (!list.isEmpty()) {
            return list;
        }
        return null;
    }

    // 1. 包含指定字符串（相当于 SQL 的 LIKE '%关键词%'）
    // Criteria criteria1 = Criteria.where("字段名").regex("关键词");
    // 2. 以指定字符串开头（相当于 SQL 的 LIKE '关键词%'）
    // Criteria criteria2 = Criteria.where("字段名").regex("^关键词");
    // 3. 以指定字符串结尾（相当于 SQL 的 LIKE '%关键词'）
    // Criteria criteria3 = Criteria.where("字段名").regex("关键词$");
    // 4. 不区分大小写的模糊查询（添加 "i" 选项）
    // Criteria criteria4 = Criteria.where("字段名").regex("关键词", "i");

    private static Query getComprehensiveQuery(ExamData examData) {
        Query query = new Query();
        if (examData == null) {
            return query;
        }
        String typeName = examData.getTypeName();
        Criteria criteria;
        if (StringUtils.isNotBlank(typeName)) {
            criteria = Criteria.where(MongoConstants.MONGO_TYPE_NAME).is(typeName);
            query.addCriteria(criteria);
        }
        String campus = examData.getCampus();
        if (StringUtils.isNotBlank(campus)) {
            criteria = Criteria.where(MongoConstants.MONGO_CAMPUS).is(campus);
            query.addCriteria(criteria);
        }
        String practiceId = examData.getPracticeId();
        if (StringUtils.isNotBlank(practiceId)) {
            criteria = Criteria.where(MongoConstants.MONGO_PRACTICE).is(practiceId);
            query.addCriteria(criteria);
        }
        String user = examData.getUser();
        if (StringUtils.isNotBlank(user)) {
            criteria  = Criteria.where(MongoConstants.MONGO_USER).is(user);
            query.addCriteria(criteria);
        }
        String date = examData.getDate();
        if (StringUtils.isNotBlank(date)) {
            criteria  = Criteria.where(MongoConstants.MONGO_TIME_SORTED).regex("^" + date);
            query.addCriteria(criteria);
        }
        return query;
    }

    @Override
    public boolean insertExamData(ExamData examData) {
        ReadingAnswer readingAnswer = new ReadingAnswer();
        readingAnswer.setUser(examData.getName());
        readingAnswer.setCampus(examData.getCampus());
        String practiceId = String.valueOf(Math.random()).substring(2);
        readingAnswer.setPracticeId(practiceId);
        readingAnswer.setTypeName(examData.getTypeName());
        readingAnswer.setTime(DateUtils.getLocalTime());
        ArrayList<ExamDataList> list = examData.getList();
        if (Objects.isNull(list)) {
            return false;
        }
        ExamRecord examRecord = new ExamRecord();
        BeanUtils.copyBeanProp(examRecord, readingAnswer);
        insertRecord(examRecord);
        list.forEach(item -> {
            readingAnswer.set_id(null);
            readingAnswer.setQuestionsText(item.getQuestionsText());
            readingAnswer.setQuestionsNumber(item.getQuestionsNumber());
            readingAnswer.setScore(item.getScore());
            readingAnswer.setUserText(item.getUserText());
            if (item.getCorrectAnswer() != 0) {
                readingAnswer.setCorrectText(null);
                readingAnswer.setCorrectAnswer(item.getCorrectAnswer());
                readingAnswer.setUserAnswer(item.getUserAnswer());
                boolean flag = item.getCorrectAnswer() == item.getUserAnswer();
                readingAnswer.setUserScore(flag ? item.getScore() : 0);
            }
            else {
                //处理文本答案
                readingAnswer.setCorrectText(item.getCorrectText());
                if (item.getCorrectText() != null && !item.getCorrectText().isEmpty()) {
                    boolean equalsIgnoreCase = item.getCorrectText().equalsIgnoreCase(item.getUserText());
                    if (equalsIgnoreCase) {
                        readingAnswer.setUserScore(item.getScore());
                    }
                    else {
                        readingAnswer.setUserScore(0);
                    }
                }
            }
            comprehensiveTemplate.insert(readingAnswer);
        });
        return true;
    }

    @Override
    public void insertRecord(ExamRecord examRecord) {
        comprehensiveTemplate.insert(examRecord);
    }

    @Override
    public void insert() {
        Reading reading = new Reading();
        reading.setTime(DateUtils.getLocalTime());
        Reading inserted = comprehensiveTemplate.insert(reading);
        ReadingQuestion readingQuestion = new ReadingQuestion();
        readingQuestion.setMain(inserted.get_id());
        readingQuestion.setTime(DateUtils.getLocalTime());
        comprehensiveTemplate.insert(readingQuestion);
        log.info("inserted {}", inserted.get_id());
    }

    @Override
    public void insert(Reading reading) {
        String text = reading.getText(); //题目“&”分割
        String option = reading.getOptions();
        reading.setText(null);
        reading.setOptions(null);
        reading.setTime(DateUtils.getLocalTime());
        int questionsNum = reading.getQuestionsNum();
        String[] texts = text.split(StringUtils.AND);
        String[] options = option.split(StringUtils.AND);
        Reading inserted = comprehensiveTemplate.insert(reading);
        for (int i = 0; i < questionsNum; i++) {
            ReadingQuestion readingQuestion = new ReadingQuestion();
            readingQuestion.setMain(inserted.get_id());
            readingQuestion.setTime(DateUtils.getLocalTime());
            readingQuestion.setQuestionsText(texts[i]);
            readingQuestion.setArticleTitle(reading.getArticleTitle());
            readingQuestion.setQuestionsOption(options[i]);
            comprehensiveTemplate.insert(readingQuestion);
        }
    }
}
